#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <Wire.h>
#include "SSD1306Wire.h"
SSD1306Wire display(0x3c, 2, 14);
const char *ssid = "0_SevDaisy Mate 10";
const char *password = "66752928";
const char *username = "1062";
const char *user_password = "1146";
ESP8266WebServer server(80);
/* Check if header is present and correct */
bool is_authenticated(){
  Serial.println("Enter is_authenticated");
  if (server.hasHeader("Cookie"))
  {
    Serial.print("Found cookie: ");
    String cookie = server.header("Cookie");
    Serial.println(cookie);
    if (cookie.indexOf("ESPSESSIONID=1") != -1)
    {
      Serial.println("Authentication Successful");
      return true;
    }
  }
  Serial.println("Authentication Failed");
  return false;
}
/* login page, also called for disconnect */
void handleLogin(){
  String msg;
  if (server.hasHeader("Cookie"))
  {
    Serial.print("Found cookie: ");
    String cookie = server.header("Cookie");
    Serial.println(cookie);
  }
  if (server.hasArg("DISCONNECT"))
  {
    Serial.println("Disconnection");
    server.sendHeader("Location", "/login");
    server.sendHeader("Cache-Control", "no-cache");
    server.sendHeader("Set-Cookie", "ESPSESSIONID=0");
    server.send(301);
    return;
  }
  if (server.hasArg("USERNAME") && server.hasArg("PASSWORD"))
  {
    if (server.arg("USERNAME") == username && server.arg("PASSWORD") == user_password)
    {
      server.sendHeader("Location", "/");
      server.sendHeader("Cache-Control", "no-cache");
      server.sendHeader("Set-Cookie", "ESPSESSIONID=1");
      server.send(301);
      Serial.println("Log in Successful");
      return;
    }
    msg = "Wrong username/password! try again.";
    Serial.println("Log in Failed");
  } /*  获取客户端IP地址 */
  WiFiClient get_client = server.client();
  Serial.println(get_client.remoteIP());
  display.clear();
  display.drawString(10, 10, "Client  IP: ");
  display.drawString(10, 26, get_client.remoteIP().toString());
  display.display();
  String content = "<html><body><h1>31801146 Lab6 T2</h1><form action='/login' method='POST'>To log in, please press button below<br>";
  content += "User:<input type='text' name='USERNAME' placeholder='user name'><br>";
  content += "Password:<input type='password' name='PASSWORD' placeholder='password'><br>";
  content += "<input type='submit' name='SUBMIT' value='Submit'></form></body></html>" + msg + "<br>";
  server.send(200, "text/html", content);
}
void gggg(){
  Serial.println("Enter gggg");
  String header;
  if (!is_authenticated())
  {
    server.sendHeader("Location", "/login");
    server.sendHeader("Cache-Control", "no-cache");
    server.send(301);
    return;
  }
  String content = "<html><body><H2>31801146 Lab6 T2</H2><br>";
  content += "IO0:" + String(digitalRead(0)) + "<br>";
  content += "</body></html>";
  server.send(200, "text/html", content);
}
/* root page can be accessed only if authentication is ok */
void handleRoot(){
  Serial.println("Enter handleRoot");
  String header;
  if (!is_authenticated())
  {
    server.sendHeader("Location", "/login");
    server.sendHeader("Cache-Control", "no-cache");
    server.send(301);
    return;
  }
  String content = "<html><body><H1>successfully connected to esp8266!</H1><h2>31801146 Lab6 T2</h2>";
  content += "IO0:" + String(digitalRead(0)) + "<br>";
  content += "IO1:" + String(digitalRead(1)) + "<br>";
  content += "You can access this page until you <a href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>";
  server.send(200, "text/html", content);
}
/* no need authentication */
void handleNotFound(){
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++)
  {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}
void setup(void){
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println(""); /*  Wait for connection */
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  server.on("/", handleRoot);
  server.on("/login", handleLogin);
  server.on("/gpio/1", gggg);
  server.onNotFound(handleNotFound); /* here the list of headers to be recorded */
  const char *headerkeys[] = {"User-Agent", "Cookie"};
  size_t headerkeyssize = sizeof(headerkeys) / sizeof(char *); /* ask server to track these headers */
  server.collectHeaders(headerkeys, headerkeyssize);
  server.begin();
  Serial.println("HTTP server started");
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_16);
}
void loop(void) { server.handleClient(); }